/*
 * WantToBuyDetailFragment.java
 * business
 *
 * Created by chentao on 2017/5/12.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.main.discovery.wanttobuydetail;

import android.content.DialogInterface;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yidiandao.business.R;
import com.yidiandao.business.base.SuperBaseEventFragment;
import com.yidiandao.business.data.WantToBuyEntity;
import com.yidiandao.business.data.bean.ShareEntity;
import com.yidiandao.business.data.event.RefreshDiscoveryWantToBuyDetailEvent;
import com.yidiandao.business.manager.ImageManager;
import com.yidiandao.business.ui.adapter.WantToBuyDetailAdapter;
import com.yidiandao.business.ui.picturescan.PictureScanActivity;
import com.yidiandao.business.ui.widget.dialog.BusinessDialog;
import com.yidiandao.business.ui.widget.dialog.OfferDialog;
import com.yidiandao.business.ui.widget.dialog.ShareDialog;
import com.yidiandao.business.ui.widget.listview.DisplayListItem;
import com.yidiandao.business.ui.widget.view.BannerView;
import com.yidiandao.business.ui.widget.view.SuperLoadingLayout;
import com.yidiandao.business.utils.ImageLoader;
import com.yidiandao.business.utils.TimeUtils;
import com.yidiandao.business.utils.UIUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import in.srain.cube.views.loadmore.LoadMoreContainer;
import in.srain.cube.views.loadmore.LoadMoreHandler;
import in.srain.cube.views.loadmore.LoadMoreListViewContainer;

/**
 * 发现-求购详情-View
 */
public class WantToBuyDetailFragment extends SuperBaseEventFragment implements WantToBuyDetailContract.View {

    private WantToBuyDetailContract.Presenter mPresenter;

    private Toolbar mToolbar;

    private TextView mTvTitle;

    private ImageButton mIbtnShare;

    private ListView mListView;

    private BannerView mBannerView;

    private ImageView mIvAvatar;

    private TextView mTvShopName;

    private TextView mTvContent;

    private TextView mTvTime;

    private TextView mTvOfferCount;

    private TextView mTvWantToBuyCount;

    private Button mBtnCommit;

    private RelativeLayout mBottomLayout;

    private WantToBuyDetailAdapter mAdapter;

    private LoadMoreListViewContainer mLoadMoreContainer;

    private String mOfferPrice;
    private String mOfferShippingFee;
    private String mOfferPhone;

    private int repeatCount;
    private String mWantToBuyUnit;

    public static WantToBuyDetailFragment getInstance() {
        WantToBuyDetailFragment fragment = new WantToBuyDetailFragment();
        return fragment;
    }

    @Override
    public void setPresenter(WantToBuyDetailContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public String getPagerTag() {
        return WantToBuyDetailFragment.class.getSimpleName();
    }

    @Override
    public void showToast(String text) {
        UIUtils.showToast(text);
    }

    @Override
    protected void initViews() {
        mToolbar = (Toolbar) mRootView.findViewById(R.id.toolbar);
        mTvTitle = (TextView) mRootView.findViewById(R.id.tv_title);
        mIbtnShare = (ImageButton) mRootView.findViewById(R.id.ibtn_share);
        mListView = (ListView) mRootView.findViewById(R.id.list_view);
        mBtnCommit = (Button) mRootView.findViewById(R.id.btn_commit);
        mBottomLayout = (RelativeLayout) mRootView.findViewById(R.id.bottom_layout);
        mLoadMoreContainer = (LoadMoreListViewContainer) mRootView.findViewById(R.id.load_more_container);

        initBanner();
        initListView();

        initListeners();
    }

    private void initBanner() {
        View headerView = View.inflate(mActivity, R.layout.item_want_to_buy_detail_banner, null);
        mBannerView = (BannerView) headerView.findViewById(R.id.banner_view);
        mIvAvatar = (ImageView) headerView.findViewById(R.id.iv_avatar);
        mTvShopName = (TextView) headerView.findViewById(R.id.tv_shop_name);
        mTvContent = (TextView) headerView.findViewById(R.id.tv_content);
        mTvTime = (TextView) headerView.findViewById(R.id.tv_time);
        mTvOfferCount = (TextView) headerView.findViewById(R.id.tv_offer_count);
        mTvWantToBuyCount = (TextView) headerView.findViewById(R.id.tv_count);

        mListView.addHeaderView(headerView);
    }

    private void initListView() {
        mAdapter = new WantToBuyDetailAdapter(mActivity);
        mListView.setAdapter(mAdapter);
    }

    private void initListeners() {
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finishActivity();
            }
        });

        mIbtnShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 分享
                mPresenter.doShare();
            }
        });

        mBtnCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 提交报价
                showOfferDialog();
            }
        });

        // 上拉加载更多
        mLoadMoreContainer.useDefaultFooter();
        mLoadMoreContainer.setLoadMoreHandler(new LoadMoreHandler() {
            @Override
            public void onLoadMore(LoadMoreContainer loadMoreContainer) {
                mPresenter.getOfferList(false, null);
            }
        });
    }

    private void showOfferDialog() {
        OfferDialog dialog = new OfferDialog(mActivity);
        dialog.show();
        dialog.setUnit(mWantToBuyUnit);
        dialog.setOnConfirmOfferInfoListener(new OfferDialog.OnConfirmOfferInfoListener() {
            @Override
            public void onConfirmOffer(String price, String shippingFee, String phone) {
                mOfferPrice = price;
                mOfferShippingFee = shippingFee;
                mOfferPhone = phone;
                mPresenter.submitOffer(price, shippingFee, phone);
            }
        });
    }

    // 设置Banner数据
    private void setBannerData(final List<String> bannerData) {
        mBannerView.setData(bannerData);

        mBannerView.setOnSingleClickListener(new BannerView.OnSingleClickListener() {
            @Override
            public void onClick(int position) {
                ImageManager.getInstance().setFinalImageList(bannerData);
                PictureScanActivity.actionStart(mActivity, position, false);
            }
        });
    }

    // 报价数量
    private void setOfferCount(int count) {
        if (count == 0) {
            mTvOfferCount.setText(R.string.no_offer);
        } else {
            mTvOfferCount.setText(UIUtils.getString(R.string.offer_count, count));
        }
    }

    @Override
    public void refreshHeader(WantToBuyEntity entity) {

        mWantToBuyUnit = entity.getUnit();

        setBannerData(entity.getPictures());
        setOfferCount(entity.getOfferCount());
        ImageLoader.loadAvatar(UIUtils.getContext(), mIvAvatar, entity.getSex());
        mTvShopName.setText(entity.getDpName());
        mTvContent.setText(entity.getDesc());
        mTvTitle.setText(entity.getDesc());
        mTvTime.setText(TimeUtils.getRelativeTimeWithSingleUnit(UIUtils.getResources(), TimeUtils.getAndroidMillis(entity.getAddTime()), true));
        mTvWantToBuyCount.setText(UIUtils.getString(R.string.want_to_buy_count, entity.getNumber(), mWantToBuyUnit));

        // 是否报价
        if (entity.getIsBelong() == 0) {
            // 不是自己发布的求购
            setBottomLayoutVisible(true);
            setBottomLayoutEnable(entity.getIsOffer() == 0);
        } else {
            // 自己发布的求购
            setBottomLayoutVisible(false);
        }
    }

    private void setBottomLayoutVisible(boolean visible) {
        mBottomLayout.setVisibility(visible ? View.VISIBLE : View.GONE);
    }

    @Override
    public void showShareDialog(ShareEntity shareEntity) {
        ShareDialog dialog = new ShareDialog(mActivity);
        dialog.setShareLinkData(shareEntity);
        dialog.show();
    }

    @Override
    public void finishActivity() {
        mActivity.finish();
    }

    @Override
    public void showSuccessDialog() {
        new BusinessDialog.Builder(mActivity)
                .setTitle(R.string.submit_offer_success)
                .setMessage(R.string.wait_for_contact)
                .setSinglePositiveButton(R.string.continue_check, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 点击提交成功
                        mPresenter.start();
                        setBottomLayoutEnable(false);
                    }
                })
                .create()
                .show();
    }

    private void setBottomLayoutEnable(boolean enable) {
        mBtnCommit.setEnabled(enable);
        if (!enable) mBtnCommit.setText(R.string.you_have_offered);
        else mBtnCommit.setText(R.string.submit_info);
    }

    @Override
    public void showFailedDialog(String message) {

        repeatCount++;

        int confirmText = (repeatCount >= 2) ? R.string.confirm : R.string.submit_again;

        new BusinessDialog.Builder(mActivity)
                .setTitle(R.string.submit_offer_failed)
                .setMessage(message)
                .setSinglePositiveButton(confirmText, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (repeatCount < 2) {
                            // 点击重新提交
                            mPresenter.submitOffer(mOfferPrice, mOfferShippingFee, mOfferPhone);
                        }
                    }
                })
                .create()
                .show();
    }

    @Override
    public void setDisplayItems(List<DisplayListItem> listItems) {
        mAdapter.setData(listItems);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mBannerView != null) {
            mBannerView.stop();
            mBannerView = null;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    @Override
    public void onEventMainThread(RefreshDiscoveryWantToBuyDetailEvent event) {
        mPresenter.start();
    }

    @Override
    public void notifyDataChanged() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_want_to_buy_detail;
    }

    @Override
    public void loadMoreFinish(boolean emptyResult, boolean hasMore) {
        mLoadMoreContainer.loadMoreFinish(emptyResult, hasMore);
    }

    @Override
    public void loadMoreError() {
        mLoadMoreContainer.loadMoreError(0, UIUtils.getString(R.string.load_more_failed));
    }

    @Override
    public void refreshContent(int result) {
        if (result == SuperLoadingLayout.STATE_SUCCESS)
            mBottomLayout.setVisibility(View.VISIBLE);
        superRefreshLayoutState(result);
    }

    @Override
    public int checkResultObject(Object resultObject) {
        return superCheckListState(resultObject);
    }

    @Override
    protected void startLoadData() {
        mPresenter.start();
    }
}
